package com.magicsoft.app.helper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.boyuan.huijiaoyu.R;
import com.magicsoft.constant.Constant;
import com.magicsoft.weitown.ui.CustomDownloadDialog;

public class ApkHelper {

	private Context context;
	private ProgressBar mProgress;
	private Dialog downloadDialog;
	private final static int DOWNLOAD_COMPLETE = 0;
	private final static int DOWNLOAD_FAIL = 1;

	private String appName;
	// 下载目录
	private File updateDir = null;
	private File updateFile = null;
	private int serverVersionNum = 1;

	// .apk下载地址
	private String clientUrlPath = "";
	private Thread thread;
	private boolean isStopThread = true;
	String TAG = "ApkHelper";
	
	public ApkHelper(Context context) {
		this.context = context;
	}

	/**
	 * 下载进度对话框
	 */
	public void showDownloadDialog() {

		downloadDialog = new CustomDownloadDialog(context, R.style.qr_dialog);
		downloadDialog.setCancelable(false);
		downloadDialog.show();
		// 标题
		TextView tv_title = (TextView) downloadDialog
				.findViewById(R.id.dialog_title);
		tv_title.setText("正在下载，请稍后...");
		// 进度条
		mProgress = (ProgressBar) downloadDialog.findViewById(R.id.progress);

		downloadApk();
	}

	/**
	 * 启动线程下载apk
	 */
	private void downloadApk() {
		serverVersionNum = Integer
				.parseInt(SharePreferenceHelper.getStringValue(context,
						SharePreferenceHelper.SERVERVERSIONNUM));

		clientUrlPath = SharePreferenceHelper.getStringValue(context,
				SharePreferenceHelper.CLIENTURLPATH);
		Log.e(TAG, "clientUrlPath =" +clientUrlPath);
		appName = context.getString(R.string.app_name);

		// 判断是否有外部存储
		if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
				.getExternalStorageState())) {
			Date date = new Date();
			String dateString = "" + (date.getMonth() + 1) + date.getDay()
					+ date.getHours() + date.getMinutes() + date.getSeconds();
			updateDir = new File(Environment.getExternalStorageDirectory(),
					Constant.downloadDir);
			Log.e(TAG, "updateDir =" +updateDir.getPath());
			// TODO:文件名需要修改
			updateFile = new File(updateDir.getPath(), "huiApp" + dateString
					+ ".apk");

		}

		// 使用新线程去下载

		thread = new Thread(new updateRunnable());
		thread.start();
	}

	private Handler updateHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWNLOAD_COMPLETE:
				// //下载完毕后安装
				// Uri uri = Uri.fromFile(updateFile);
				// Intent installIntent = new Intent(Intent.ACTION_VIEW);
				// installIntent.setDataAndType(uri,
				// "application/vnd.android.package-archive");
				//

				if (isStopThread) {

					installApk();
				}

			case DOWNLOAD_FAIL:
				// 下载失败处理
				if (downloadDialog != null) {
					downloadDialog.dismiss();
				}
			default:
			}

		}
	};

	class updateRunnable implements Runnable {
		Message message = updateHandler.obtainMessage();
		@Override
		public void run() {
			Log.e(TAG, "updateRunnable message="+message);
			message.what = DOWNLOAD_COMPLETE;
			try {
				// <uses-permission
				// android:name="android.permission.WRITE_EXTERNAL_STORAGE">;
				if (!updateDir.exists()) {
					updateDir.mkdirs();
				}
				if (!updateFile.exists()) {
					updateFile.createNewFile();
				}

				// <uses-permission
				// android:name="android.permission.INTERNET">;
				long downloadSize = downloadUpdateFile(clientUrlPath,
						updateFile);
				if (downloadSize > 0) {
					// 下载完毕通知
					updateHandler.sendMessage(message);
					Log.e(TAG, "downloadSize > 0 updateRunnable message="+message);
					// SharePreferenceHelper.setStringValue(getApplicationContext(),
					// SharePreferenceHelper.LOCALVERSIONNUM,
					// ""+serverVersionNum);
				}
			} catch (Exception ex) {
				ex.printStackTrace();

				message.what = DOWNLOAD_FAIL;
				// 下载失败通知
				updateHandler.sendMessage(message);
			}

		}
	}

	/**
	 * 安装APK
	 */
	private void installApk() {

		if (!updateFile.exists()) {
			Log.e(TAG, "APK文件不存在");
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + updateFile.toString()),
				"application/vnd.android.package-archive");

		context.startActivity(i);
		android.os.Process.killProcess(android.os.Process.myPid());// 如果不加上这句的话在apk安装完成之后点击单开会崩溃
	}

	// 下载文件
	public long downloadUpdateFile(String downloadUrl, File saveFile)
			throws Exception {

		int downloadCount = 0;
		int currentSize = 0;
		long totalSize = 0;
		int updateTotalSize = 0;

		HttpURLConnection httpConnection = null;
		InputStream is = null;
		FileOutputStream fos = null;

		try {
			URL url = new URL(downloadUrl);
			httpConnection = (HttpURLConnection) url.openConnection();
			httpConnection
					.setRequestProperty("User-Agent", "PacificHttpClient");
			if (currentSize > 0) {
				httpConnection.setRequestProperty("RANGE", "bytes="
						+ currentSize + "-");
			}
			httpConnection.setConnectTimeout(10000);
			httpConnection.setReadTimeout(20000);
			updateTotalSize = httpConnection.getContentLength();
			if (httpConnection.getResponseCode() == 404) {
				throw new Exception("fail!");
			}
			is = httpConnection.getInputStream();
			fos = new FileOutputStream(saveFile, false);
			byte buffer[] = new byte[4096];
			int readsize = 0;
			while ((readsize = is.read(buffer)) > 0) {
				fos.write(buffer, 0, readsize);
				totalSize += readsize;
				// 更新下载进度 eg:10%
				if ((downloadCount == 0)
						|| (int) (totalSize * 100 / updateTotalSize) - 10 > downloadCount) {
					downloadCount += 10;
					mProgress.setProgress(downloadCount);
				}
			}
		} finally {
			if (httpConnection != null) {
				httpConnection.disconnect();
			}
			if (is != null) {
				is.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
		return totalSize;
	}
}